package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

/**
 * mybatis拦截器
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class AutoFillCreateInfoPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {


        Object parameter = invocation.getArgs()[1];
        Executor statementHandler = (Executor) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
       // MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 检查是否存在 skipAutoFill 标识

        // 或者解析SQL语句来判断是否为INSERT
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        String sql = boundSql.getSql();
        // 只处理插入操作
        if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT) {
            // 判断是否为需要自动填充的实体类型
            if (parameter instanceof BaseEntity) {
                BaseEntity entity = (BaseEntity) parameter;
                if (null !=ServletUtils.getRequest()) {
                    LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
                    // 设置createBy和createTime
                    entity.setCreateBy(loginUser.getUser().getUserId().toString()); // 替换为实际值或从SecurityContext等获取
                    entity.setCreateTime(new Date());

                    // 更新参数
                    invocation.getArgs()[1] = entity;
                }
            }


            if (parameter instanceof HashMap) {
                Object entities = ((HashMap<?, ?>) parameter).get("entities");
                if (entities instanceof Collection && !(entities instanceof String)) {
                    Collection<?> collection = (Collection<?>) entities;
                    boolean isBaseEntityCollection = collection.stream().allMatch(item -> item instanceof BaseEntity);

                    if (isBaseEntityCollection) {
                        collection.forEach(item -> {
                            BaseEntity entity = (BaseEntity) item;
                            if (entity.getCreateBy() == null) {
                                if (null !=ServletUtils.getRequest()) {
                                    LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
                                    // 设置createBy和createTime
                                    entity.setCreateBy(loginUser.getUser().getUserId().toString()); // 替换为实际值或从SecurityContext等获取
                                }
                            }
                            if (entity.getCreateTime() == null) {
                                entity.setCreateTime(new Date());
                            }
                        });

                    }
                }
            }

        }

        return invocation.proceed();
    }


    private Method getMethodFromInvocation(Invocation invocation) {
        try {
            // 通过反射获取目标对象的类
            Class<?> targetClass = invocation.getTarget().getClass();

            // 获取方法签名
            Method signature =  invocation.getMethod();

            // 通过反射获取实际方法
            return targetClass.getMethod(signature.getName(), signature.getParameterTypes());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Failed to retrieve the method from the invocation.", e);
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在此处添加插件所需的属性配置
    }
}
